package codec;

import bean.DemoProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.handler.codec.MessageToMessageCodec;

import java.util.List;

/**
 * Created by momochen on 2017-07-31.
 */
public class DemoProtocolCodec extends ByteToMessageCodec<DemoProtocol> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, DemoProtocol demoProtocol, ByteBuf byteBuf) throws Exception {
//        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();

        byteBuf.writeInt(demoProtocol.getHead_data());
        byteBuf.writeInt(demoProtocol.getContentLength());
        byteBuf.writeBytes(demoProtocol.getContent());
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
//        //标记读指针位置，以便可以回滚指针
//        byteBuf.markReaderIndex();
//
//        //如果读取的包长度不够head_length，回滚指针不做处理，等待下个包再解析
//        if (byteBuf.readableBytes() < 9) {
//            byteBuf.resetReaderIndex();
//            return;
//        }

        DemoProtocol demoProtocol = new DemoProtocol();
        demoProtocol.setHead_data(byteBuf.readInt());
        demoProtocol.setContentLength(byteBuf.readInt());

        byte[] bytes = new byte[demoProtocol.getContentLength()];
        byteBuf.readBytes(bytes);
        demoProtocol.setContent(bytes);

        list.add(demoProtocol);
    }
}
